package com.wangyf.thread.c_021_question;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

/**
 * 写一个题目: 一个线程添加10个元素到容器 另一个线程监听容器 到5个的时候打印后停止
 * Created by feng on 2021/1/16.
 * 使用 LockSupport 实现
 */
public class T05_LockSupport {

    static Thread t1 = null,t2 = null;

    public static void main(String[] args) throws InterruptedException {
        List<Object> list = new ArrayList<>();

        t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                list.add(new Object());
                System.out.println(list.size());
                if (list.size() == 5) {
                    LockSupport.unpark(t2);
                    LockSupport.park();
                }
            }
        });
        t2 = new Thread(() -> {
            System.out.println("t2 begin");
            LockSupport.park();
            LockSupport.unpark(t1);
            System.out.println("t2 end");
        });

        t2.start();
        // 这里需要注意  需要让t2 park  再让 t1启动 假如 t2未park，t1执行了.unpark(t2); 那么 t2会永远 park()
        Thread.sleep(100);
        t1.start();

    }
}
